import axios from "axios";
import { ElMessageBox } from "element-plus";
import utils from "xe-utils";

let version: string = "";
let isConfirming = false;

interface VersionDto {
  version: string;
}

const onCheckUpdate = utils.debounce(() => {
  checkUpdate();
}, 4000);

function checkUpdate() {
  axios<VersionDto>({
    url: location.origin + "/version.json?t=" + new Date().valueOf(),
  }).then(({ data }) => {
    if (!version) {
      version = data.version;
    } else if (version != data.version) {
      if (isConfirming) return;
      isConfirming = true;

      ElMessageBox.confirm("发现新版本, 是否更新?", "提示")
        .then(() => {
          location.reload();
          isConfirming = false;
        })
        .catch(() => {
          isConfirming = false;
        });
    }
  });
}

export function startCheckUpdate() {
  onCheckUpdate();
  window.addEventListener("focus", () => {
    onCheckUpdate();
  });
  document.addEventListener("visibilitychange", () => {
    onCheckUpdate();
  });

  window.addEventListener("error", (e: any) => {
    if (e.target && e.target.tagName?.toLowerCase() === "script") {
      onCheckUpdate();
    }
  });
}
